/*
 * Copyright(C) 2013-2017 AZ ALL Rights Reserved.
 *
 * FileName: Login
 * 
 * Description: xxxxx
 *
 * History:
 * 版本号                作者      日期      操作
 * 1.0       ZhouFan             2017/10/16 0016   
 *  
 */
package com.az.shiro.ice.action;

import com.az.shiro.ice.console.Console;
import com.az.shiro.ice.domain.User;
import com.az.shiro.ice.service.UserService;
import com.az.shiro.ice.spring.ApplicationContextInstance;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author ZhouFan
 * @version 1.0
 * @date 2017/10/16 0016
 * @see
 */
public class SystemOperation {

    private Console console = new Console();

    private boolean isLogined = Boolean.FALSE;
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:app.xml");
        UserService userService = (UserService) context.getBean("userService");
        User user = new User("Jesse", "123456");

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());

        subject.login(token);
        context.close();
    }

    public Subject login(String username, String password) {

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            Session session = subject.getSession();
            console.println("Session Id: " + session.getId());
            console.println(session.getTimeout());
            isLogined = true;
        } catch (UnknownAccountException e1) {
            console.println(Console.none_account_label);
        } catch (LockedAccountException e2) {
            console.println(Console.account_locked_label);
        } catch (IncorrectCredentialsException e3) {
            console.println(Console.incorrect_credentials_label);
        }
        return subject;
    }

    public boolean isLogined() {
        return isLogined;
    }
}

 